package afeng.world.pangu.bio;

import lombok.SneakyThrows;
import org.junit.jupiter.api.Test;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
import java.util.Date;

public class IOClient {

  public static void main(String[] args) {
    // TODO 创建多个线程，模拟多个客户端连接服务端
    Thread thread = new Thread(() -> {
      try {
        Socket socket = new Socket("127.0.0.1", 3333);
        while (true) {
          try {
            socket.getOutputStream().write((new Date() + ": hello world").getBytes());
            Thread.sleep(2000);
          } catch (Exception e) {
          }
        }
      } catch (IOException e) {
      }
    });
    thread.start();
//    new IOClient().wget();

  }

  /**
   * 网络下载
   */
  @SneakyThrows
  @Test
  public void wget(){
    File file = new File("wget.html");
    Socket socket = new Socket();
    SocketAddress socketAddress = new InetSocketAddress("xin", 80);
    socket.connect(socketAddress,3000);
    InputStream inputStream = socket.getInputStream();
    byte[] bytes = new byte[1024];
    int len ;
//    FileOutputStream fo = new FileOutputStream(file);
    while((len = inputStream.read(bytes)) !=-1){ // todo 阻塞, 需要发送get请求
      System.out.println(" = " + new String(bytes,0,len));
//      fo.write(bytes);
    }
//    fo.close();
  }

}